# coding=utf-8
# 编译日期：2022-08-05 09:43:59
# 版权所有：www.i-search.com.cn
import time
import pdb
from ubpa.ilog import ILog
from ubpa.base_img import *
import getopt
from sys import argv
import sys
import datetime as mydate
import os as myos
import re	
import traceback
import ubpa.iautomation as iautomation
import ubpa.ibrowse as ibrowse
import ubpa.ichrome_firefox as ichrome_firefox
import ubpa.iclipboard as iclipboard
import ubpa.ikeyboard as ikeyboard
import ubpa.iwin as iwin

class Dserver:
     
    def __init__(self,**kwargs):
        self.__logger = ILog(__file__)
        self.path = set_img_res_path(__file__)
        self.robot_no = ''
        self.proc_no = ''
        self.job_no = ''
        self.input_arg = ''
        if('robot_no' in kwargs.keys()):
            self.robot_no = kwargs['robot_no']
        if('proc_no' in kwargs.keys()):
            self.proc_no = kwargs['proc_no']
        if('job_no' in kwargs.keys()):
            self.job_no = kwargs['job_no']
        if('input_arg' in kwargs.keys()):
            self.input_arg = kwargs['input_arg']
            self.input_arg = self.input_arg.replace("\\","/")
        self.templateDictFile=None
        self.driver=None
        self.imgPath=None
        self.configFile=None
        self.templateUploadFile=None
        self.dom_text=None
        self.sftp_list=[]
        self.chromePath=r"C:\Program Files\Google\Chrome\Application\chrome.exe"
        self.PassWord=None
        self.UserName=None
        self.taskDir=r'D:\RPA\接口文档/'
        self.organizeUrl=[]
        self.originalUrl=[]
        self.Arrpath1=r'D:\RPA\temp\ty\Do/'
        self.Temppath=r"D:\RPA\temp\PO单通用数据结构.xlsx"
        self.Configdir=r"D:\RPA\temp/"
        self.Sftpdir='sftp://mysftp@47.118.52.110/upload/dev/'
        self.Arrpath=r'D:\RPA\temp\cyc\Do/'
        self.Movedir=r"D:\RPA\temp\cyc\Downloadfile/"
        self.Downdir=r'C:\Users\xxxx\Downloads/'
        self.configList=None
        self.Token=[]
        self.Interface=[]
        self.Datadic={'供应商':['C272—上汽变速器'],'出货地':['A2'],'状态':['已出货'],'到货指示时间起':['2021-06-30']}
        self.TemplateCode=None
        self.client=None
        self.userList=None
        self.sysCode=None
        self.callbackUrl="http://sit.sccp.mastr.top:61517/sccp-web-api-sit/openapi/rpa/callback"
        self.taskId=None
        self.robot_status=r'D:\RPA\接口文档\机器人状态.txt'
        self.Txtrob=r'D:\RPA\接口文档\接口数据.txt'
      
    def GetData_dfqc(self):
        '''[Group]:东风启程\ndfqc_po.xls'\n'''
        judge=None
        img=None
        index=1
        box=[1,2,3,6,10,11]
        vlist=[]
        vlist1=[]
        values=None
        i=None
        name=None
        temp=None
        # Try异常
        self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815343757619,Note:')
        try:
            # 代码块
            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815344063325,Note:由所需字段及其xpath索引及其类型的字典')
            print(self.Datadic)
            filter_dict={
            '供应商':{'xpath':'1','type':'5','values':[]},
            '出货地':{'xpath':'2','type':'5','values':[]},
            '要货方':{'xpath':'3','type':'5','values':[]},
            '状态':{'xpath':'6','type':'5','values':[]},
            '物流商':{'xpath':'10','type':'5','values':[]},
            '营业所':{'xpath':'11','type':'5','values':[]},
            }
            dataList=[]
            #到货指示时间起
            try:
                time_start=self.Datadic['到货指示时间起'][0]
            except:
                time_start=''
            #到货指示时间止
            try:
                time_end=self.Datadic['到货指示时间止'][0]
            except:
                time_end=''
            now_new=mydate.datetime.now().strftime("%Y_%m_%d %H:%M:%S")
            now_new=now_new.replace(" ",'_').replace(":","_")
            save_file_path=myos.path.join(self.Downdir,'订单操作履历查询.xls')
            print(save_file_path)
            up_file_path=myos.path.join(self.Movedir,str(self.taskId),"source",'%sdfqc_po.xls' % now_new)
            print(up_file_path)
            if not myos.path.exists(myos.path.join(self.Movedir,str(self.taskId),"source")):
                myos.makedirs(myos.path.join(self.Movedir,str(self.taskId),"source"))
            if myos.path.isfile(save_file_path):
               myos.remove(save_file_path)
            # 序列
            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815343910022,Note:序列')
            # For循环
            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:081534304485,Note:for循环20次')
            for item_081534304485 in range(20):
                # Try异常
                self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:081534289132,Note:异常')
                try:
                    # 鼠标点击
                    self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815343858821,Note:点击 国产供货协同')
                    time.sleep(5)
                    ichrome_firefox.do_click_pos_chrome(attrMap={"aaname":"4 国产供货协同","aastate":"enabled","css-selector":"body>div>div>div>div>ul>li>a>font"},index=0,title=r'管理平台',url=r'https://scmp.dongfeng-nissan.com.cn/MP.aspx',button=r'left',curson=r'center',times=5,run_mode=r'unctrl',waitfor=10)
                    time.sleep(4)
                    # 鼠标点击
                    self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815343807820,Note:订单管理')
                    time.sleep(3)
                    ichrome_firefox.do_click_pos_chrome(attrMap={"aaname":"4-2 订单管理","aastate":"enabled","css-selector":"body>div>div>div>div>ul>li>ul>li>a"},index=0,title=r'管理平台',url=r'https://scmp.dongfeng-nissan.com.cn/MP.aspx',button=r'left',curson=r'center',times=5,run_mode=r'unctrl',waitfor=10)
                    time.sleep(4)
                    # 鼠标点击
                    self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815343706318,Note:点击4-2-9订单履历查询')
                    time.sleep(3)
                    ichrome_firefox.do_click_pos_chrome(attrMap={"aaname":"4-2-9 订单操作履历查询","aastate":"enabled","css-selector":"body>div>div>div>div>ul>li>ul>li>ul>li>a"},index=0,title=r'管理平台',url=r'https://scmp.dongfeng-nissan.com.cn/MP.aspx',button=r'left',curson=r'center',times=5,run_mode=r'unctrl',waitfor=10)
                    time.sleep(4)
                    # 获取文本
                    self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815343655217,Note:获取 4-2-9订单履历查询')
                    time.sleep(3)
                    tvar0815343655217 = ichrome_firefox.get_element_val_chrome(attrMap={"aaname":"4-2-9 订单操作履历查询","aastate":"enabled","css-selector":"body>div>div>div>div","id":"titleText","xpath":"//*[@id=\"titleText\"]"},index=0,title=r'管理平台',url=r'https://scmp.dongfeng-nissan.com.cn/MP.aspx',waitfor=20)
                    time.sleep(1)
                    # IF-N分支
                    self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:081534299384,Note:是否为空')
                    if tvar0815343655217:
                        # Break中断
                        self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:081534294243,Note:中断')
                        break
                    else:
                        # 热键输入
                        self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:081534283991,Note:刷新')
                        time.sleep(1)
                        ikeyboard.key_send_cs(win_title=r'管理平台 - Google Chrome',text='{F5}',waitfor=10)
                        time.sleep(5)
                except Exception as e:
                    # 代码块
                    self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:2613284463311,Note:判断网页是否关闭')
                    errorname=traceback.format_exc()
                    print(errorname)
                    # IF-N分支
                    self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:2613284463310,Note:')
                    if 'do_win_activate error' in errorname:
                        # Raise抛出异常
                        self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:2613284463312,Note:raise抛出异常')
                        raise e
                    else:
                        pass
                finally:
                    pass
            # For循环
            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815344469533,Note:循环数据字典获取数据')
            for (k,v) in filter_dict.items():
                # 代码块
                self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815344368131,Note:count=1')
                count=1
                # 鼠标点击
                self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815343452113,Note:点击全部')
                time.sleep(0.5)
                ichrome_firefox.do_click_pos_chrome(attrMap={"aastate":"enabled","css-selector":"body>div>div>div>div>div>table>tbody>tr>td>div>div>div>div>table>tbody>tr>td>div","xpath":"//*[@id=\"selectofTextLYComboBox%s\"]"%v['xpath']},index=0,title=r'管理平台',url=r'https://scmp.dongfeng-nissan.com.cn/QS/Webform/default/zh-CN/F_a6ef3530fd2144a0815ba942a653a1c7.htm?formid=F_a6ef3530fd2144a0815ba942a653a1c7&caller=5&status=5&menuID=b0a43110-5d93-46cd-8543-b0c24687c0ba&rd=V1.23.3&_rd=0.8317028142517262',button=r'left',curson=r'center',times=1,run_mode=r'unctrl',waitfor=10)
                time.sleep(1)
                # While循环
                self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815344418432,Note:while循环')
                while 1:
                    # Try异常
                    self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815344317330,Note:')
                    try:
                        # 获取文本
                        self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815344114726,Note:获取内容文本')
                        values = ichrome_firefox.get_element_val_chrome(attrMap={"xpath":"//*[@id=\"LYComboBox{}\"]/option[{}]".format(v['xpath'],count)},index=0,title=r'管理平台',url=r'https://scmp.dongfeng-nissan.com.cn/QS/Webform/default/zh-CN/F_a6ef3530fd2144a0815ba942a653a1c7.htm?formid=F_a6ef3530fd2144a0815ba942a653a1c7&caller=5&status=5&menuID=b0a43110-5d93-46cd-8543-b0c24687c0ba&rd=V1.23.3&_rd=0.10002734237234834',waitfor=3)
                        # IF-N分支
                        self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815343553715,Note:判断json中是否存下此参数')
                        if values==self.Datadic[k][0]:
                            # 鼠标点击
                            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815343605016,Note:点击')
                            time.sleep(0.5)
                            selectorJson = {"selector":[{"ControlType":"文本","ControlTypeID":"0xC364","Index":"1"},{"ControlType":"列表项目","ControlTypeID":"0xC357","Index":"%s"%count},{"ControlType":"列表","ControlTypeID":"0xC358","Index":"1"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"4"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"1"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"1"},{"ControlType":"文档","ControlTypeID":"0xC36E","Index":"1"},{"ControlType":"窗格","ControlTypeID":"0xC371","Index":"1"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"1"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"2"},{"ControlType":"对话框","ControlTypeID":"0xC369","Index":"1"},{"ControlType":"文档","ControlTypeID":"0xC36E","Index":"1"}]}
                            
                            iautomation.do_click(win_class=r'Chrome_WidgetWin_1',win_name=r'管理平台 - Google Chrome',selector=selectorJson,button=r'left',curson=r'center',offsetX=0,offsetY=0,times=2,run_mode=r'unctrl',search_depth=2,waitfor=10)
                            time.sleep(0.5)
                            # Break中断
                            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815343502514,Note:中断')
                            break
                        else:
                            # 代码块
                            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815344215728,Note:更新变量count')
                            count+=1
                            
                    except Exception as e:
                        # Break中断
                        self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815344266929,Note:中断')
                        break
                    finally:
                        pass
            # Try异常
            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:24175050153635,Note:try异常')
            try:
                # 鼠标点击
                self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:24174334888604,Note:点击开始日期1')
                time.sleep(1.5)
                ichrome_firefox.do_click_pos_chrome(attrMap={"aaname":"到货指示时间起","aastate":"enabled","controltype":"LYDateBox","css-selector":"body>div>div>div>div>div>table>tbody>tr>td>div>div>div>input","xpath":"//*[@id=\"LYDateBox1\"]"},index=0,title=r'管理平台',url=r'https://scmp.dongfeng-nissan.com.cn/QS/Webform/default/zh-CN/F_a6ef3530fd2144a0815ba942a653a1c7.htm?formid=F_a6ef3530fd2144a0815ba942a653a1c7&caller=5&status=5&menuID=b0a43110-5d93-46cd-8543-b0c24687c0ba&rd=V1.23.3&_rd=0.1305199019900396',button=r'left',curson=r'center',times=2,run_mode=r'unctrl',waitfor=10)
                time.sleep(1.5)
                # 鼠标点击
                self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:24174334888603,Note:清空1')
                time.sleep(0.5)
                selectorJson = {"selector":[{"ControlType":"按钮","ControlTypeID":"0xC350","Index":"1"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"3"},{"ControlType":"文档","ControlTypeID":"0xC36E","Index":"1"},{"ControlType":"窗格","ControlTypeID":"0xC371","Index":"1"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"2"},{"ControlType":"文档","ControlTypeID":"0xC36E","Index":"1"},{"ControlType":"窗格","ControlTypeID":"0xC371","Index":"1"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"1"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"2"},{"ControlType":"对话框","ControlTypeID":"0xC369","Index":"1"},{"ControlType":"文档","ControlTypeID":"0xC36E","Index":"1"}]}
                iautomation.do_click(win_class=r'Chrome_WidgetWin_1',win_name=r'管理平台 - Google Chrome',selector=selectorJson,button=r'left',curson=r'center',offsetX=0,offsetY=0,times=1,run_mode=r'ctrl',search_depth=20,waitfor=20)
                time.sleep(0.5)
            except Exception as e:
                # 鼠标点击
                self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:24175108858640,Note:点击开始日期2')
                time.sleep(1.5)
                ichrome_firefox.do_click_pos_chrome(attrMap={"aaname":"到货指示时间起","aastate":"enabled","controltype":"LYDateBox","css-selector":"body>div>div>div>div>div>table>tbody>tr>td>div>div>div>input","xpath":"//*[@id=\"LYDateBox1\"]"},index=0,title=r'管理平台',url=r'https://scmp.dongfeng-nissan.com.cn/QS/Webform/default/zh-CN/F_a6ef3530fd2144a0815ba942a653a1c7.htm?formid=F_a6ef3530fd2144a0815ba942a653a1c7&caller=5&status=5&menuID=b0a43110-5d93-46cd-8543-b0c24687c0ba&rd=V1.23.3&_rd=0.1305199019900396',button=r'left',curson=r'center',times=2,run_mode=r'unctrl',waitfor=10)
                time.sleep(1.5)
                # 鼠标点击
                self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:24175108858639,Note:清空2')
                time.sleep(0.5)
                selectorJson = {"selector":[{"ControlType":"按钮","ControlTypeID":"0xC350","Index":"1"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"3"},{"ControlType":"文档","ControlTypeID":"0xC36E","Index":"1"},{"ControlType":"窗格","ControlTypeID":"0xC371","Index":"1"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"2"},{"ControlType":"文档","ControlTypeID":"0xC36E","Index":"1"},{"ControlType":"窗格","ControlTypeID":"0xC371","Index":"1"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"1"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"2"},{"ControlType":"对话框","ControlTypeID":"0xC369","Index":"1"},{"ControlType":"文档","ControlTypeID":"0xC36E","Index":"1"}]}
                iautomation.do_click(win_class=r'Chrome_WidgetWin_1',win_name=r'管理平台 - Google Chrome',selector=selectorJson,button=r'left',curson=r'center',offsetX=0,offsetY=0,times=1,run_mode=r'ctrl',search_depth=20,waitfor=20)
                time.sleep(0.5)
            finally:
                pass
            #拷贝到剪贴板
            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815344824540,Note:起始时间')
            iclipboard.set_clipboard(text=time_start)
            # 热键输入
            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815344875941,Note:粘贴')
            ikeyboard.key_send_cs(text='^v',waitfor=10)
            # 鼠标点击
            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815344570735,Note:点击结束日期')
            time.sleep(1.5)
            ichrome_firefox.do_click_pos_chrome(attrMap={"aaname":"到货指示时间止","aastate":"enabled","controltype":"LYDateBox","css-selector":"body>div>div>div>div>div>table>tbody>tr>td>div>div>div>input","xpath":"//*[@id=\"LYDateBox2\"]"},index=0,title=r'管理平台',url=r'https://scmp.dongfeng-nissan.com.cn/QS/Webform/default/zh-CN/F_a6ef3530fd2144a0815ba942a653a1c7.htm?formid=F_a6ef3530fd2144a0815ba942a653a1c7&caller=5&status=5&menuID=b0a43110-5d93-46cd-8543-b0c24687c0ba&rd=V1.23.3&_rd=0.19436286808591463',button=r'left',curson=r'center',times=2,run_mode=r'unctrl',waitfor=10)
            time.sleep(1.5)
            # 鼠标点击
            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815345027444,Note:清空结束日期')
            time.sleep(0.5)
            selectorJson = {"selector":[{"ControlType":"按钮","ControlTypeID":"0xC350","Index":"1"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"3"},{"ControlType":"文档","ControlTypeID":"0xC36E","Index":"1"},{"ControlType":"窗格","ControlTypeID":"0xC371","Index":"1"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"2"},{"ControlType":"文档","ControlTypeID":"0xC36E","Index":"1"},{"ControlType":"窗格","ControlTypeID":"0xC371","Index":"1"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"1"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"2"},{"ControlType":"对话框","ControlTypeID":"0xC369","Index":"1"},{"ControlType":"文档","ControlTypeID":"0xC36E","Index":"1"}]}
            iautomation.do_click(win_class=r'Chrome_WidgetWin_1',win_name=r'管理平台 - Google Chrome',selector=selectorJson,button=r'left',curson=r'center',offsetX=0,offsetY=0,times=1,run_mode=r'ctrl',search_depth=20,waitfor=20)
            time.sleep(0.5)
            #拷贝到剪贴板
            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815344925942,Note:结束时间')
            iclipboard.set_clipboard(text=time_end)
            # 热键输入
            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815344976243,Note:拷贝结束时间')
            ikeyboard.key_send_cs(text='^v',waitfor=10)
            # 鼠标点击
            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815344672137,Note:车型')
            ichrome_firefox.do_click_pos_chrome(attrMap={"aaname":"车型：","aastate":"enabled","css-selector":"body>div>div>div>div>div>table>tbody>tr>td>div>div>div>label","id":"LYLabel15","xpath":"//*[@id=\"LYLabel15\"]"},index=0,title=r'管理平台',url=r'https://scmp.dongfeng-nissan.com.cn/QS/Webform/default/zh-CN/F_a6ef3530fd2144a0815ba942a653a1c7.htm?formid=F_a6ef3530fd2144a0815ba942a653a1c7&caller=5&status=5&menuID=b0a43110-5d93-46cd-8543-b0c24687c0ba&rd=V1.23.3&_rd=0.021600792236818434',button=r'left',curson=r'center',times=1,run_mode=r'unctrl',waitfor=10)
            # 鼠标点击
            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:24144633709146,Note:')
            time.sleep(3)
            ichrome_firefox.do_click_pos_chrome(attrMap={"aaname":"查询","aastate":"enabled","css-selector":"body>div>div>div>table>tbody>tr>td>div>span","id":"lbLYFormListButton1","isleaf":"1","parentid":"LYFormListButton1","parentname":"0","parenttag":"DIV","readystate":"1","role":"element","selecteditems":"{  }","tableCol":"1","tableRow":"1","tag":"SPAN","xpath":"//*[@id=\"lbLYFormListButton1\"]"},index=0,title=r'管理平台',url=r'https://scmp.dongfeng-nissan.com.cn/QS/Webform/default/zh-CN/F_a6ef3530fd2144a0815ba942a653a1c7.htm?formid=F_a6ef3530fd2144a0815ba942a653a1c7&caller=5&status=5&menuID=b0a43110-5d93-46cd-8543-b0c24687c0ba&rd=V1.23.3&_rd=0.31165843624325573',button=r'left',curson=r'center',times=1,run_mode=r'ctrl',waitfor=10)
            time.sleep(3)
            # 鼠标点击
            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815344723438,Note:导出')
            time.sleep(2)
            ichrome_firefox.do_click_pos_chrome(attrMap={"aaname":"导出","aastate":"enabled","css-selector":"body>div>div>div>table>tbody>tr>td>div>span","id":"lbLYFormListButton2","isleaf":"1","parentid":"LYFormListButton2","parentname":"0","parenttag":"DIV","readystate":"1","role":"element","selecteditems":"{  }","tableCol":"2","tableRow":"1","tag":"SPAN","xpath":"//*[@id=\"lbLYFormListButton2\"]"},index=0,title=r'管理平台',url=r'https://scmp.dongfeng-nissan.com.cn/QS/Webform/default/zh-CN/F_a6ef3530fd2144a0815ba942a653a1c7.htm?formid=F_a6ef3530fd2144a0815ba942a653a1c7&caller=5&status=5&menuID=b0a43110-5d93-46cd-8543-b0c24687c0ba&rd=V1.23.3&_rd=0.19436286808591463',button=r'left',curson=r'center',times=1,run_mode=r'ctrl',waitfor=10)
            time.sleep(5)
            # Try异常
            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815345180647,Note:导出是否异常')
            try:
                # 获取文本
                self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815345230748,Note:当前是否有误数据')
                selectorJson = {"selector":[{"ControlType":"文本","ControlTypeID":"0xC364","Index":"1"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"1"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"2"},{"ControlType":"对话框","ControlTypeID":"0xC369","Index":"1"},{"ControlType":"文档","ControlTypeID":"0xC36E","Index":"1"},{"ControlType":"窗格","ControlTypeID":"0xC371","Index":"1"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"1"},{"ControlType":"组","ControlTypeID":"0xC36A","Index":"2"},{"ControlType":"对话框","ControlTypeID":"0xC369","Index":"1"},{"ControlType":"文档","ControlTypeID":"0xC36E","Index":"1"}]}
                iautomation.get_text(win_name=r'管理平台 - Google Chrome',selector=selectorJson,return_field=r'value',search_depth=2,waitfor=10)
                # 鼠标点击
                self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815345129146,Note:确定')
                ichrome_firefox.do_click_pos_chrome(attrMap={"aaname":"确定"},index=0,title=r'管理平台',url=r'https://scmp.dongfeng-nissan.com.cn/QS/Webform/default/zh-CN/F_a6ef3530fd2144a0815ba942a653a1c7.htm?formid=*',button=r'left',curson=r'center',times=1,run_mode=r'unctrl',waitfor=10)
                # Return返回
                self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:081534314637,Note:')
                return None
            except Exception as e:
                # 热键输入
                self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:1411200695923,Note:去掉下载框')
                time.sleep(3)
                ikeyboard.key_send_cs(text='!w',waitfor=10)
                # 热键输入
                self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815345078545,Note:刷新')
                time.sleep(1)
                ikeyboard.key_send_cs(win_title=r'管理平台 - Google Chrome',text='{F5}',waitfor=10)
                time.sleep(5)
            finally:
                pass
            # 代码块
            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815344773639,Note:处理数据')
            import pandas as pd
            import shutil
            from openpyxl import load_workbook
            import datetime
            shutil.copyfile(save_file_path, up_file_path)
            try:
                if not myos.path.exists(myos.path.join(self.Movedir,str(self.taskId),"arrange")):
                    myos.makedirs(myos.path.join(self.Movedir,str(self.taskId),"arrange"))
                arrange_file_path = myos.path.join(self.Movedir,str(self.taskId),"arrange",myos.path.basename(up_file_path).replace(".xls","_整理后.xlsx"))
                shutil.copyfile(self.templateUploadFile,arrange_file_path)
            except Exception as e:
                print(str(e))
                raise Exception("")
            condic = ""
            try:
                with open(self.templateDictFile,'r',encoding='utf-8') as f:
                    condic = f.read()
            except:
                with open(self.templateDictFile, 'rb') as f:
                    condic = f.read()
            condic = eval(condic)
            wb = load_workbook(arrange_file_path)
            ws = wb['Sheet1']
            read_df = pd.read_excel(up_file_path,dtype='str')
            #read_df = read_df.dropna(axis=0, subset=['交货单号'])
            write_df = pd.read_excel(arrange_file_path, sheet_name='Sheet1', header=None)
            headers = write_df.loc[0].values.tolist()
            print(headers)
            none_list = ['客户工厂', '虚拟零件号', '发货单行号', '计划提货时间']
            allrow = read_df.shape[0]
            print(allrow)
            try:
                dlist1 = []
                for row in range(allrow):
                    dlist = []
                    for index, col in enumerate(headers):
                        if col in condic:
                            val = read_df[condic[col]]
                            if col.endswith("时间"):
                                if len(str(val.values.tolist()[row])) == 16:
                                    dlist.append(val.values.tolist()[row] + ":00")
                                else:
                                    dlist.append(val.values.tolist()[row])
                            else:
                                dlist.append(val.values.tolist()[row])
                        elif col == "订单行号":
                            dlist.append(1)
                        elif col == "单据类型":
                            dlist.append(10)
                        elif col == "写入时间":
                            now = str(datetime.datetime.now())
                            dlist.append(now)
                        elif col == "网址简称":
                            dlist.append(self.TemplateCode)
                            
                        elif col in none_list:
                            dlist.append(" ")
                    code = 0
                    kaccount = 1
                    for i in self.Interface:
                        for k, v in i.items():
                            if k == "plantId" and v == "":
                                dlist.insert(3, i['customerCode'])
                                dlist.insert(15, '')
                                dlist.insert(16, i['plantId'])
                                dlist.insert(17, i['shippingBay'])
                                dlist.insert(18, i['salesOrganization'])
                                dlist.insert(19, i['distributionChannel'])
                                dlist.insert(20, i['productGroup'])
                                dlist.insert(21, i['shippingPoint'])
                                code = 1
                                break
                        if code == 1:
                            break
                        if kaccount == len(self.Interface):
                            print('主数据未能匹配！！！！！')
                            print('主数据未能匹配！！！！！')
                            print('主数据未能匹配！！！！！')
                            dlist.insert(3, ' ')
                            dlist.insert(15, ' ')
                            dlist.insert(16, ' ')
                            dlist.insert(17, ' ')
                            dlist.insert(18, ' ')
                            dlist.insert(19, ' ')
                            dlist.insert(20, ' ')
                            dlist.insert(21, ' ')
                            continue
                        kaccount += 1
                    dlist1.append(dlist)
                aaa = []
                for ii in dlist1:
                    bbb = [' ' if i == 'nan' or i == None else i for i in ii]
                    aaa.append(bbb)
                ccc = []
                for i in aaa:
                    # print(i)
                    if i not in ccc:
                        ws.append(i)
                    ccc.append(i)
                wb.save(arrange_file_path)
            except Exception as e:
                print(str(e))
                raise Exception("")
            
            # 代码块
            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815343401012,Note:上传sftp')
            time.sleep(2)
            # coding: utf-8
            import paramiko
            import re
            import os
            import datetime
            from time import sleep
            class Linux(object):
                # 通过IP, 用户名，密码，超时时间初始化一个远程Linux主机
                def __init__(self, ip, username, password, timeout=3000):
                    self.ip = ip
                    self.username = username
                    self.password = password
                    self.timeout = timeout
                    # transport和chanel
                    self.t = ''
                    self.chan = paramiko.Transport((ip, 22))
                    # 链接失败的重试次数
                    self.try_times = 3
                # 调用该方法连接远程主机
                def connect(self):
                    while True:
                        # 连接过程中可能会抛出异常，比如网络不通、链接超时
                        try:
                            self.t = paramiko.Transport(sock=(self.ip, 22))
                            self.t.connect(username=self.username, password=self.password)
                            self.chan = self.t.open_session()
                            self.chan.settimeout(self.timeout)
                            self.chan.get_pty()
                            self.chan.invoke_shell()
                            # 如果没有抛出异常说明连接成功，直接返回
                            print(u'连接%s成功' % self.ip)
                            # 接收到的网络数据解码为str
                            print(self.chan.recv(65535).decode('utf-8'))
                            return
                        # 这里不对可能的异常如socket.error, socket.timeout细化，直接一网打尽
                        except Exception as e1:
                            if self.try_times != 0:
                                print(u'连接%s失败，进行重试' % self.ip)
                                self.try_times -= 1
                            else:
                                print(u'重试3次失败，结束程序')
                                exit(1)
                # 断开连接
                def close(self):
                    self.chan.close()
                    self.t.close()
                # ------获取本地指定目录及其子目录下的所有文件------
                def __get_all_files_in_local_dir(self, local_dir):
                    # 保存所有文件的列表
                    all_files = list()
                    # 获取当前指定目录下的所有目录及文件，包含属性值
                    files = os.listdir(local_dir)
                    for x in files:
                        # local_dir目录中每一个文件或目录的完整路径
                        filename = os.path.join(local_dir, x)
                        # 如果是目录，则递归处理该目录
                        if os.path.isdir(x):
                            all_files.extend(self.__get_all_files_in_local_dir(filename))
                        else:
                            all_files.append(filename)
                    return all_files
                def sftp_put_dir(self, local_dir, remote_dir):
                    t = paramiko.Transport(sock=(self.ip, 22))
                    t.connect(username=self.username, password=self.password)
                    sftp = paramiko.SFTPClient.from_transport(t)
                    # 去掉路径字符穿最后的字符'/'，如果有的话
                    if remote_dir[-1] == '/':
                        remote_dir = remote_dir[0:-1]
                    # 获取本地指定目录及其子目录下的所有文件
                    # 依次put每一个文件
                    filename = os.path.basename(local_dir)
                    print('filename::',filename)
                    remote_filename = remote_dir  + '/'+filename
                    print(remote_filename)
                    print(u'Put文件%s传输到%s中...' % (filename, self.ip))
                    print(remote_filename)
                    print('local_dir',local_dir)
                    print('remote_filename',remote_filename)
                    sftp.put(local_dir, remote_filename)
                    print('发送成功')
            if __name__ == '__main__':
                remote_path_1 = self.sftp_list[0][1]
                remote_path = remote_path_1 + '/organize'
                remote_path_originalUrl =remote_path_1+ '/original'
                #local_path = arr_path
                for x in self.sftp_list:
                    print(x)
                    host = Linux(x[0], x[2], x[3])
                    host.sftp_put_dir(arrange_file_path, remote_path)
                    host.sftp_put_dir(up_file_path, remote_path_originalUrl)
                    self.organizeUrl.append(remote_path + '/' + os.path.basename(arrange_file_path))
                    self.originalUrl.append(remote_path_originalUrl + '/'+ os.path.basename(up_file_path))
                    print(self.organizeUrl)
                    print(self.originalUrl)
                    #host.close()
        except Exception as e:
            # 子流程:error
            self.__logger.debug('Flow:GetData_dfqc,StepNodeTag:0815343349711,Note:"东风启辰下载数据失败！请立即查看"')
            (temptemp)=self.error(detail="东风启辰下载数据失败！请立即查看",text="东风启辰下载数据失败！请立即查看")
        finally:
            pass
      
    def Get_yzm(self):
        '''[Group]:东风启程\n'''
        mail_time=None
        mail_page=None
        img=None
        msg=None
        # 代码块
        self.__logger.debug('Flow:Get_yzm,StepNodeTag:2414250539524,Note:获取时间判断是邮件时间')
        import datetime
        now_minute=int((datetime.datetime.now()-datetime.timedelta(seconds=70)).minute)
        print(now_minute)
        # Try异常
        self.__logger.debug('Flow:Get_yzm,StepNodeTag:2414250182917,Note:')
        try:
            # 序列
            self.__logger.debug('Flow:Get_yzm,StepNodeTag:241424572308,Note:')
            #打开浏览器
            self.__logger.debug('Flow:Get_yzm,StepNodeTag:241424556865,Note:打开邮箱网站')
            mail_page = ibrowse.open_browser(browser_type='chrome',url=self.mail_path,path=self.chromePath,param="--test-type --ignore-certificate-errors")
            # 代码块
            self.__logger.debug('Flow:Get_yzm,StepNodeTag:071222534231,Note:密码self.mail_pwd')
            print('密码self.mail_pwd',self.mail_pwd)
            # 设置文本
            self.__logger.debug('Flow:Get_yzm,StepNodeTag:241424567167,Note:开始登录输入账号')
            time.sleep(1)
            ichrome_firefox.set_element_val_chrome(attrMap={"aastate":"enabled","aria-labelledby":"userNameLabel","css-selector":"body>form>div>div>div>div>input","id":"username","isleaf":"1","name":"username","parentid":"lgnDiv","parentname":"logonForm","parenttag":"DIV","readystate":"1","role":"element","selecteditems":"{  }","tag":"INPUT","url":"https://webmail.sagw.com/owa/auth/logon.aspx?replaceCurrent=1&url=https%3a%2f%2fwebmail.sagw.com%2fowa","xpath":"//*[@id=\"username\"]"},index=0,title=r'Outlook',url=r'https://webmail.sagw.com/owa/auth/logon.aspx?replaceCurrent=1&url=https%3a%2f%2fwebmail.sagw.com%2fowa',text=self.mail_user,waitfor=10)
            # 设置文本
            self.__logger.debug('Flow:Get_yzm,StepNodeTag:241424577429,Note:输入密码  改')
            ichrome_firefox.set_element_val_chrome(attrMap={"aastate":"enabled","aria-labelledby":"passwordLabel","css-selector":"body>form>div>div>div>div>input","id":"password","isleaf":"1","name":"password","onfocus":"g_fFcs=0","parentid":"lgnDiv","parentname":"logonForm","parenttag":"DIV","readystate":"1","role":"element","selecteditems":"{  }","tag":"INPUT","type":"password","url":"https://webmail.sagw.com/owa/auth/logon.aspx?replaceCurrent=1&url=https%3a%2f%2fwebmail.sagw.com%2fowa","xpath":"//*[@id=\"password\"]"},index=0,title=r'Outlook',url=r'https://webmail.sagw.com/owa/auth/logon.aspx?replaceCurrent=1&url=https%3a%2f%2fwebmail.sagw.com*',text=self.mail_pwd,waitfor=10)
            # 鼠标点击
            self.__logger.debug('Flow:Get_yzm,StepNodeTag:2414250335120,Note:点击登录按钮')
            time.sleep(2)
            ichrome_firefox.do_click_pos_chrome(attrMap={"aaname":"登录","aastate":"enabled","css-selector":"body>form>div>div>div>div>div>span","isleaf":"1","parentid":"lgnDiv","parentname":"logonForm","parenttag":"DIV","readystate":"1","role":"element","selecteditems":"{  }","tag":"SPAN","url":"https://webmail.sagw.com/owa/auth/logon.aspx?replaceCurrent=1&url=https%3a%2f%2fwebmail.sagw.com%2fowa","xpath":"//*[@id=\"lgnDiv\"]/div[9]/div[1]/span[1]"},index=0,title=r'Outlook',url=r'https://webmail.sagw.com/owa/auth/logon.aspx?replaceCurrent=1&url=https%3a%2f%2fwebmail.sagw.com%2fowa',button=r'left',curson=r'center',times=1,run_mode=r'ctrl',waitfor=10)
            time.sleep(2)
            # 鼠标点击
            self.__logger.debug('Flow:Get_yzm,StepNodeTag:2414245825310,Note:搜索转发人')
            time.sleep(5)
            ichrome_firefox.do_click_pos_chrome(attrMap={"aaname":"搜索邮件和人员","aastate":"enabled","css-selector":"body>div>div>div>div>div>div>div>div>div>div>div>div>button>span","xpath":"//*[@id=\"primaryContainer\"]/div[5]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[2]/button[1]/span[2]"},index=0,title=r'邮件 - yy@sagw.com',url=r'https://webmail.sagw.com/owa/#path=/mail/inbox',button=r'left',curson=r'center',times=1,run_mode=r'unctrl',waitfor=10)
            time.sleep(2)
            # 键盘输入
            self.__logger.debug('Flow:Get_yzm,StepNodeTag:241424546703,Note:模拟按键输入检索人名')
            time.sleep(1.5)
            ikeyboard.key_send_cs(text=self.mail_send,waitfor=10)
            time.sleep(0.5)
            # 鼠标点击
            self.__logger.debug('Flow:Get_yzm,StepNodeTag:2414245876711,Note:点击搜索')
            time.sleep(0.5)
            ichrome_firefox.do_click_pos_chrome(attrMap={"aaname":" ","aastate":"enabled","css-selector":"body>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>button>span","xpath":"//*[@id=\"primaryContainer\"]/div[5]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/button[1]/span[1]"},index=0,title=r'邮件 - yy@sagw.com',url=r'https://webmail.sagw.com/owa/#path=/mail/inbox',button=r'left',curson=r'center',times=1,run_mode=r'unctrl',waitfor=10)
            time.sleep(0.5)
            # For循环
            self.__logger.debug('Flow:Get_yzm,StepNodeTag:2414250846530,Note:循环：获取最新邮件')
            for item_2414250846530 in range(20):
                # 鼠标点击
                self.__logger.debug('Flow:Get_yzm,StepNodeTag:2414250795029,Note:打开最上面的邮件')
                time.sleep(1)
                ichrome_firefox.do_click_pos_chrome(attrMap={"aaname":"费泳飞","aastate":"enabled","autoid":"_lvv_5","css-selector":"body>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>span>span"},index=0,title=r'邮件 - yy@sagw.com',url=r'https://webmail.sagw.com/owa/#path=/mail/search',button=r'left',curson=r'center',times=1,run_mode=r'ctrl',waitfor=10)
                # 获取文本
                self.__logger.debug('Flow:Get_yzm,StepNodeTag:2414250743428,Note:获取邮件时间')
                time.sleep(3)
                mail_time = ichrome_firefox.get_element_val_chrome(attrMap={"aastate":"enabled","css-selector":"body>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>span","isleaf":"1","parentid":"primaryContainer","parenttag":"DIV","readystate":"1"},index=0,title=r'邮件 - yy@sagw.com',url=r'https://webmail.sagw.com/owa/#path=/mail/search',waitfor=10)
                time.sleep(3)
                # IF-N分支
                self.__logger.debug('Flow:Get_yzm,StepNodeTag:2414250692227,Note:判断邮件分钟是否大于判断时间')
                if int(mail_time.split(':')[-1])>=now_minute:
                    # Break中断
                    self.__logger.debug('Flow:Get_yzm,StepNodeTag:2414250642026,Note:时间满足退出循环')
                    break
                else:
                    # 热键输入
                    self.__logger.debug('Flow:Get_yzm,StepNodeTag:2414250591025,Note:F5刷新页面')
                    ikeyboard.key_send_cs(win_title=r'邮件 - yy@sagw.com - Google Chrome',text='{F5}',waitfor=10)
                    time.sleep(10)
            # 鼠标点击
            self.__logger.debug('Flow:Get_yzm,StepNodeTag:2414245927912,Note:打开最上面的邮件')
            time.sleep(1)
            ichrome_firefox.do_click_pos_chrome(attrMap={"aaname":"费泳飞","aastate":"enabled","autoid":"_lvv_5","css-selector":"body>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>span>span"},index=0,title=r'邮件 - yy@sagw.com',url=r'https://webmail.sagw.com/owa/#path=/mail/search',button=r'left',curson=r'center',times=1,run_mode=r'unctrl',waitfor=10)
            time.sleep(3)
            # 获取文本
            self.__logger.debug('Flow:Get_yzm,StepNodeTag:2414245978413,Note:获取邮件文本')
            time.sleep(1)
            msg = ichrome_firefox.get_element_val_chrome(attrMap={"aaname":"    ","aastate":"enabled","css-selector":"body>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div>div","xpath":"//*[@id=\"Item.MessageUniqueBody\"]/div[1]/div[1]"},index=0,title=r'邮件 - yy@sagw.com',url=r'https://webmail.sagw.com/owa/#path=/mail/search',waitfor=10)
            # 代码块
            self.__logger.debug('Flow:Get_yzm,StepNodeTag:2414250080415,Note:正则匹配验证码')
            yzm=re.search(r'\d{6}',msg).group(0)
            print(yzm)
            #关闭浏览器tab
            self.__logger.debug('Flow:Get_yzm,StepNodeTag:241424541622,Note:关闭邮件网页')
            ibrowse.close_tab(browser=mail_page)
            # Return返回
            self.__logger.debug('Flow:Get_yzm,StepNodeTag:2414250131616,Note:return:验证码')
            return yzm
        except Exception as e:
            #关闭浏览器tab
            self.__logger.debug('Flow:Get_yzm,StepNodeTag:241424551714,Note:异常关闭邮箱页面')
            ibrowse.close_tab(browser=mail_page)
        finally:
            pass
      
    def Login_dfqc(self):
        '''[Group]:东风启程\n'''
        msg=None
        img=None
        account='CC272A1ZXRTM'
        password='Sagw@210303'
        png2=None
        position=None
        png1=None
        td=None
        # 代码块
        self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414254158045,Note:赋值流程成功判断变量：judge')
        judge=True
        #下面循环登录
        # For循环
        self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414254209646,Note:循环登录东风启程')
        for count in range(1):
            # Try异常
            self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414253904040,Note:尝试登录网站')
            try:
                # 序列
                self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414254618554,Note:')
                # 代码块
                self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414254974761,Note:关闭网页')
                import os
                os.system("taskkill /im chrome.exe")
                print(self.log_path)
                print(self.chromePath)
                
                #打开浏览器
                self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414254006742,Note:打开东风启程')
                self.driver = ibrowse.open_browser(browser_type='chrome',url=self.log_path,path=self.chromePath,param="--test-type --ignore-certificate-errors")
                time.sleep(0.2)
                # 最大化窗口
                self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414253955541,Note:最大化窗口')
                iwin.do_win_maximize(win_title=r' Google Chrome',win_text=r'',waitfor=10)
                # 设置文本
                self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414255025462,Note:输入用户')
                ichrome_firefox.set_element_val_chrome(attrMap={"aastate":"enabled","css-selector":"body>div>div>div>div>div>div>div>div>div>div>div>div>input","id":"_username_username","isleaf":"1","onkeydown":"window.keyup_submit(event,?local_auth?);","parentid":"container","parenttag":"DIV","placeholder":"请输入登录账号/邮箱","readystate":"1","role":"element","selecteditems":"{  }","tag":"INPUT","type":"text","url":"https://sso-esuppliers.dongfeng-nissan.com.cn/esc-sso/login","xpath":"//*[@id=\"_username_username\"]"},index=0,title=r'东风日产身份认证平台',url=r'https://sso-esuppliers.dongfeng-nissan.com.cn/esc-sso/login',text=self.user,waitfor=10)
                # 设置文本
                self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414255075663,Note:输入密码')
                ichrome_firefox.set_element_val_chrome(attrMap={"aastate":"enabled","css-selector":"body>div>div>div>div>div>div>div>div>div>div>div>div>input","id":"_username_password","isleaf":"1","onkeydown":"window.keyup_submit(event,?local_auth?);","parentid":"container","parenttag":"DIV","placeholder":"请输入密码","readystate":"1","role":"element","selecteditems":"{  }","tag":"INPUT","type":"password","url":"https://sso-esuppliers.dongfeng-nissan.com.cn/esc-sso/login","xpath":"//*[@id=\"_username_password\"]"},index=0,title=r'东风日产身份认证平台',url=r'https://sso-esuppliers.dongfeng-nissan.com.cn/esc-sso/login',text=self.pwd,waitfor=10)
                # 鼠标点击
                self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414255125664,Note:点击登录')
                time.sleep(2)
                ichrome_firefox.do_click_pos_chrome(attrMap={"aaname":"登录","aastate":"enabled","css-selector":"body>div>div>div>div>div>div>div>div>div>div","id":"usernamaSubmit","isleaf":"1","parentid":"container","parenttag":"DIV","readystate":"1","role":"element","selecteditems":"{  }","tag":"DIV","url":"https://sso-esuppliers.dongfeng-nissan.com.cn/esc-sso/login","xpath":"//*[@id=\"usernamaSubmit\"]"},index=0,title=r'东风日产身份认证平台',url=r'https://sso-esuppliers.dongfeng-nissan.com.cn/esc-sso/login',button=r'left',curson=r'center',times=1,run_mode=r'ctrl',waitfor=10)
                # Try异常
                self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414253801038,Note:尝试获取密码错误信息')
                try:
                    pass
                except Exception as e:
                    pass
                finally:
                    pass
                # Try异常
                self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414255328768,Note:判断是否需要邮箱验证码 ')
                try:
                    # 获取文本
                    self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414255177165,Note:获取需要邮箱验证码文本')
                    tvar2414255177165 = ichrome_firefox.get_element_val_chrome(attrMap={"aaname":"请填写邮箱验证码","aastate":"enabled","css-selector":"body>div>div>div"},index=0,title=r'东风日产身份认证平台',url=r'https://sso-esuppliers.dongfeng-nissan.com.cn/esc-sso/login',waitfor=10)
                    time.sleep(5)
                    # IF-N分支
                    self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414255227366,Note:判断是否登录邮箱获取验证码')
                    if tvar2414255177165:
                        # 子流程:Get_yzm
                        self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414254466051,Note:获取验证码')
                        (tvar2414254466051)=self.Get_yzm()
                        # 鼠标点击
                        self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414254311948,Note:点击输入验证码')
                        ichrome_firefox.do_click_pos_chrome(attrMap={"aastate":"enabled","css-selector":"body>div>div>div>input","xpath":"//*[@id=\"tel1\"]"},index=0,title=r'东风日产身份认证平台',url=r'https://sso-esuppliers.dongfeng-nissan.com.cn/esc-sso/login',button=r'left',curson=r'center',times=1,run_mode=r'unctrl',waitfor=10)
                        # 键盘输入
                        self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414254363449,Note:输入验证码')
                        time.sleep(0.5)
                        ikeyboard.key_send_cs(win_title=r'东风日产身份认证平台 - Google Chrome',text=tvar2414254466051,waitfor=10)
                        time.sleep(0.5)
                    else:
                        pass
                except Exception as e:
                    pass
                finally:
                    pass
                # 鼠标点击
                self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414255378869,Note:点击进入scmp系统')
                time.sleep(0.3)
                ichrome_firefox.do_click_pos_chrome(attrMap={"css-selector":"body>div>div>div>div>div>div>div>div>div>div","id":"app_1","isleaf":"0","oncontextmenu":"return false;","parentid":"app","parenttag":"DIV","readystate":"1","role":"element","selecteditems":"{  }","tag":"DIV","xpath":"//*[@id=\"app_1\"]"},index=0,title=r'自助服务平台',url=r'https://sso-esuppliers.dongfeng-nissan.com.cn/esc-selfcare/#/',button=r'left',curson=r'center',times=1,run_mode=r'unctrl',waitfor=10)
                time.sleep(0.3)
                # 鼠标点击
                self.__logger.debug('Flow:Login_dfqc,StepNodeTag:1809370213723,Note:点击量产')
                time.sleep(0.3)
                ichrome_firefox.do_click_pos_chrome(attrMap={"aaname":"*：CC272A1ZXRTM","aastate":"enabled","css-selector":"body>div>div>div>div>div>div>div>div>div>div>div>span","data-value":"CC272A1ZXRTM","isleaf":"1","parentid":"ssoUserList","parenttag":"DIV","readystate":"1","role":"element","selecteditems":"{  }","tag":"SPAN","title":"自助服务平台","url":"https://sso-esuppliers.dongfeng-nissan.com.cn/esc-selfcare/#/","xpath":"//*[@id=\"ssoUserList\"]/span[2]"},index=0,title=r'自助服务平台',url=r'https://sso-esuppliers.dongfeng-nissan.com.cn/esc-selfcare/#/',button=r'left',curson=r'center',times=1,run_mode=r'unctrl',waitfor=10)
                time.sleep(0.3)
                # 获取文本
                self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414253597634,Note:')
                time.sleep(3)
                tvar2414253597634 = ichrome_firefox.get_element_val_chrome(attrMap={"xpath":"//*[@id=\"bottomtool-personalname\"]/span[1]"},index=0,title=r'管理平台',url=r'https://scmp.dongfeng-nissan.com.cn/MP.aspx',waitfor=10)
                time.sleep(3)
                # IF-N分支
                self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414254821558,Note:判断是否登录流程正常登录')
                if tvar2414253597634:
                    # 代码块
                    self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414254056843,Note:登录成功，设置流程判断变量')
                    judge=None
                    # Break中断
                    self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414254260647,Note:')
                    break
                else:
                    pass
            except Exception as e:
                # 代码块
                self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414255531572,Note:关闭网页')
                time.sleep(10)
            finally:
                pass
        # IF-N分支
        self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414254106944,Note:判断流程是否成功')
        if judge:
            # 子流程:error
            self.__logger.debug('Flow:Login_dfqc,StepNodeTag:2414255481471,Note:')
            (temptemp)=self.error(detail='登录失败',text='登录失败')
        else:
            pass
      
    def Parsing_Json(self):
        # Try异常
        self.__logger.debug('Flow:Parsing_Json,StepNodeTag:021241044682,Note:')
        try:
            # 代码块
            self.__logger.debug('Flow:Parsing_Json,StepNodeTag:021241044683,Note:')
            import pandas as pd
            try:
                with open(self.Txtrob,'r',encoding='utf-8') as f:
                    jsondic = f.read().split('\n')[-1]
            except:
                with open(self.Txtrob,'r') as f:
                    jsondic = f.read().split('\n')[-1]    
            print(jsondic)    
            jsondic = eval(jsondic)
            print(jsondic)
            print(type(jsondic))
             
            #jsondic = {'TaskId': 22341, 'TemplateCode': 'W01004','Data': {'UserList': [{'username': '653811398', 'password': 'Sagw202101', 'ConfigList': []}]}}
            #jsondic = {'TaskId': 22341, 'TemplateCode': 'W01001', 'Data': {'UserList': [{'username': 'user1', 'password': 'pass1', 'config_list': [{'params1': 'v1', 'params2': 'v2'}, {'params1': 'v1', 'params2': 'v3'}]}, {'username': 'user2', 'password': 'pass2', 'config_list': [{'params1': 'v1', 'params2': 'v2'}, {'params1': 'v3', 'params2': 'v4'}]}]}}
            #self.Token = jsondic['token']
            self.TemplateCode = jsondic['templateCode']
            print('TemplateCode',self.TemplateCode)
            self.taskId = jsondic['taskId']
            print(self.taskId)
            self.callbackUrl = jsondic['callbackUrl']
            print(self.callbackUrl)
            self.userList = jsondic['data']['userList']
            print('这儿',self.userList)
            # self.configList = jsondic['data']['userList']
            try:
                self.sysCode = self.Data['sysCode']
                self.client = self.Data['client']
            except:
                pass    
            df_initialize3 = pd.read_excel(r'D:\RPA\configFile\configFile_saas.xlsx',sheet_name = 'templateCode')
            for idx, row in df_initialize3.iterrows():
                if row['template_code'] == self.TemplateCode:
                    self.templateUploadFile = row['上传数据模板']
                    self.templateDictFile = row['映射字典']
            
        except Exception as e:
            # 子流程:error
            self.__logger.debug('Flow:Parsing_Json,StepNodeTag:0211435576567,Note:')
            (temptemp)=self.error(text="Json解析失败！！！！")
        finally:
            pass
      
    def error(self,detail=None,text=None):
        '''异常处理流程\n'''
        # 代码块
        self.__logger.debug('Flow:error,StepNodeTag:0211300351931,Note:发送失败邮件')
        import smtplib
        import datetime
        from PIL import ImageGrab
        from email.mime.text import MIMEText
        from email.header import Header
        from email.mime.multipart import MIMEMultipart
        import pandas as pd
        try:
            dfInitialize = pd.read_excel(self.configFile, sheet_name = 'Email')
            image_name = str(self.taskId) + "_" + datetime.datetime.now().strftime("%Y%m%d%H%M%S") + ".png"
            image_path = self.imgPath + image_name
            # 截图整个屏幕, 保存到配置文件那里的地址, 文件名相同则覆盖
            image_plan = ImageGrab.grab()
            image_plan.save(image_path)
            mailserver =  dfInitialize['发送者邮箱服务器'].values.tolist()[0]
            port = dfInitialize['端口号'].values.tolist()[0]
            username_send = dfInitialize['发送者'].values.tolist()[0]
            password = dfInitialize['授权码'].values.tolist()[0]
            username_recv = dfInitialize['接收者'].values.tolist()[0]  # 收件人，多个收件人用逗号隔开
            env = dfInitialize['所属环境'].values.tolist()[0]  # 收件人，多个收件人用逗号隔开
            
            mail = MIMEMultipart()
            mail['Subject'] = '%s-网页下载相关流程失败' % env
            mail['From'] = username_send
            mail['To'] = username_recv
            message1 = MIMEText('taskId为%s' % str(self.taskId),'plain' ,'utf-8')
            mail.attach(message1)
            img_content = ""
            with open(image_path, "rb") as f:
                img_content = f.read()
            image_att = MIMEText(img_content, "base64", "utf-8")
            image_att["Content-Type"] = "application/octet-stream"
            image_att.add_header('Content-Disposition', 'attachment', filename=image_name)
            mail.attach(image_att)
            try:
                smtp = smtplib.SMTP(mailserver, port=port)
            except:
                smtp = smtplib.SMTP_SSL(mailserver, port=port)
            smtp.login(username_send, password)
            smtp.sendmail(username_send, username_recv.split(','), mail.as_string())
            smtp.quit()
            print('success')
        except Exception as e:
            print("邮件任务发送失败")
            print(str(e))
        
        # 代码块
        self.__logger.debug('Flow:error,StepNodeTag:0211305579934,Note:回调')
        # ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        #coding=utf-8
        import requests,json
        headers = {'Content-Type': 'application/json'}
        status = 1
        if self.TemplateCode == 'COMNW0040105':
            status = 0
        data = {
                "token":"a fox jumps over the lazy dog",
                "taskId": self.taskId,
                "templateCode": self.TemplateCode,
                "status": status,
                "originalUrl": self.originalUrl,
                "organizeUrl": self.organizeUrl,
                "message": text,
                "detail":text,                           # 和邮件报警内容保持一致，由传递的参数决定
                "data": ['']
        }
        s = requests.session()
        s.keep_alive = False
        res = requests.post(self.callbackUrl,data=json.dumps(data),headers = headers)
        print(res.text)   
            
        try:
            with open(self.taskDir+str(self.taskId)+'.txt','w',encoding='utf-8') as f:
                f.write(str(data))
        except:
            with open(self.taskDir+str(self.taskId)+'.txt','wb') as f:
                f.write(str(data))
        try:
            with open(self.robot_status,'w',encoding='utf-8') as f:
                f.write('1')
        except:
            with open(self.robot_status,'wb') as f:
                f.write('1')
            
            
        
        # 代码块
        self.__logger.debug('Flow:error,StepNodeTag:121018175512,Note:杀进程退出')
        import sys
        import os
        os.system("taskkill /im chrome.exe")
        os.system("taskkill /im iexplore.exe")
        sys.exit(-1)
      
    def Main(self):
        re=None
        # Try异常
        self.__logger.debug('Flow:Main,StepNodeTag:171642064732,Note:设置主流程异常')
        try:
            # 代码块
            self.__logger.debug('Flow:Main,StepNodeTag:2709572107698,Note:初始化参数配置')
            import pandas as pd
            import os
            os.system("taskkill  /im chrome.exe")
            # os.system(r'D:\RPA\RDP.bat')
            self.configFile = r'D:\RPA\configFile\configFile_saas.xlsx'
            dfInitialize = pd.read_excel(self.configFile, sheet_name = 'DServer')
            self.Movedir = dfInitialize['文件下载整理路径'].values.tolist()[0]
            self.Downdir = dfInitialize['windows下载文件夹路径'].values.tolist()[0]
            dfInitialize1 = pd.read_excel(self.configFile, sheet_name = 'Common')
            self.taskDir = dfInitialize1['接口数据'].values.tolist()[0]
            self.robot_status = dfInitialize1['机器人状态文件'].values.tolist()[0]
            self.Txttob = dfInitialize1['接口数据文档'].values.tolist()[0]
            self.chromePath = dfInitialize1['chrome浏览器路径'].values.tolist()[0]
            self.imgPath = dfInitialize1['截图存储路径'].values.tolist()[0]
            print("获取sftp相关配置")
            df_initialize2 = pd.read_excel(self.configFile, sheet_name = 'SftpConfig')
            for idx, row in df_initialize2.iterrows():
                self.sftp_list.append([row['sftp主机IP'],row['sftp路径'],row['sftp账号'],row['sftp密码']])
                
                
                
            
            # 子流程:Parsing_Json
            self.__logger.debug('Flow:Main,StepNodeTag:0212450969522,Note:解析json')
            (temptemp)=self.Parsing_Json()
            # For循环
            self.__logger.debug('Flow:Main,StepNodeTag:1615240219221,Note:遍历userList')
            for master_data in self.userList:
                # 代码块
                self.__logger.debug('Flow:Main,StepNodeTag:1615240219220,Note:')
                self.UserName = master_data['username']
                self.PassWord = master_data['password']
                try:
                    self.configList = master_data['configList'][0]
                except:
                    print('没有主数据！')    
                    print('没有主数据！')    
                    print('没有主数据！')    
                #print(self.configList)
                try:
                    configl = []
                    configl.append(self.configList['dataFilter'])
                    print(configl)
                    self.Interface.append(self.configList['dimSales'])   
                    print('self.Interface',self.Interface)
                    print('self.Interface',self.Interface)
                    print('self.Interface',self.Interface)
                    print('self.Interface',self.Interface)
                except:
                    pass
                    print('无主数据！！')    
                    print('无主数据！！')    
                    print('无主数据！！')    
                    print('无主数据！！')    
                    print('无主数据！！')    
                configl = configl[0]
                self.Interface = self.Interface[0]
                #print(configl)    
                print(self.Interface)    
                # 序列
                self.__logger.debug('Flow:Main,StepNodeTag:1615454176344,Note:')
                # 代码块
                self.__logger.debug('Flow:Main,StepNodeTag:241138495194,Note:东风变量')
                #jsondic = {'TaskId': 22341, 'TemplateCode': 'COMNW0030001','Data': {'UserList': [{'username': 'C27221004', 'password': 'Sagw@210706', 'config_list': [{'params1': 'v1', 'params2': 'v2'}, {'params1': 'v1', 'params2': 'v3'}]}, {'username': 'user2', 'password': 'pass2', 'config_list': [{'params1': 'v1', 'params2': 'v2'}, {'params1': 'v3', 'params2': 'v4'}]}]}}
                """
                self.TemplateCode = jsondic['TemplateCode']
                print('TemplateCode',self.TemplateCode)
                self.taskId = jsondic['TaskId']
                print(self.taskId)
                self.callbackUrl = jsondic['callbackUrl']
                print(self.callbackUrl)
                self.userList = jsondic['Data']['UserList']
                print(self.userList)
                """
                #东风网页地址
                self.log_path='https://sso-esuppliers.dongfeng-nissan.com.cn/esc-sso/login'
                #user
                self.user=self.userList[0]['username']
                #self.user='C27221004'
                #pwd
                self.pwd=self.userList[0]['password']
                #self.pwd='Sagw@210706'
                #configl={'到货指示时间起':['2021-08-11'],'到货指示时间止':['2021-09-11'],'供应商':['全部'],'出货地':['全部'],'要货方':['全部'],'状态':['全部'],'物流商':['全部'],'营业所':['全部']}
                #configl={'供应商':['全部'],'结算期间_始':['2020-08-11'],'结算期间_末':['2021-09-11'],'工厂':['全部'],'清单状态':['全部'],'客户名称':['全部']}
                #邮箱地址
                #self.mail_path=r'https://webmail.sagw.com/owa/auth/logon.aspx?replaceCurrent=1&url=https%3a%2f%2fwebmail.sagw.com%2fowa%2f'
                self.mail_path=r'https://webmail.sagw.com/owa/auth/logon.aspx'
                #邮箱账号 
                self.mail_user=r'yy1@sagw.com'
                #邮箱密码
                self.mail_pwd=r'Sagw1234'
                #发件人
                self.mail_send=r'费泳飞'
                
                # IF-N分支
                self.__logger.debug('Flow:Main,StepNodeTag:23191359366142,Note:判断是否是东风启程登录')
                if self.TemplateCode.startswith('COMNW0030'):
                    # 子流程:Login_dfqc
                    self.__logger.debug('Flow:Main,StepNodeTag:23191610535148,Note:东风启程登录')
                    (temptemp)=self.Login_dfqc()
                else:
                    pass
                # For循环
                self.__logger.debug('Flow:Main,StepNodeTag:1615240219219,Note:')
                for self.Datadic in configl:
                    # 序列
                    self.__logger.debug('Flow:Main,StepNodeTag:021245096959,Note:')
                    # IF-N分支
                    self.__logger.debug('Flow:Main,StepNodeTag:23191644786149,Note:COMNW0030102')
                    if self.TemplateCode=='COMNW0030102':
                        # 子流程:GetData_dfqc
                        self.__logger.debug('Flow:Main,StepNodeTag:23191755601156,Note:东风启辰PO流程')
                        (temptemp)=self.GetData_dfqc()
                    else:
                        pass
                # 代码块
                self.__logger.debug('Flow:Main,StepNodeTag:1615551996481,Note:for循环configl任务完成')
                time.sleep(5)
                import os
                os.system("taskkill /im chrome.exe")
                time.sleep(2)
                # os.system("taskkill /im iexplore.exe")
                
            # 代码块
            self.__logger.debug('Flow:Main,StepNodeTag:3017063062363,Note:遍历数据，回调')
            # ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            #coding=utf-8
            import requests,json
            headers = {'Content-Type': 'application/json'}
            data = {
                    "token":"a fox jumps over the lazy dog",
                    "taskId": self.taskId,
                    "templateCode": self.TemplateCode,
                    "status": 0,
                    "originalUrl": self.originalUrl,
                    "organizeUrl": self.organizeUrl,
                    "message": "",
                    "detail":"",
                    "data": ['']
            }
            s = requests.session()
            s.keep_alive = False
            res = requests.post(self.callbackUrl,data=json.dumps(data),headers = headers)
            print(res.text)   
            try:
                with open(self.taskDir+str(self.taskId)+'.txt','w',encoding='utf-8') as f:
                    f.write(str(data))
            except:
                with open(self.taskDir+str(self.taskId)+'.txt','wb') as f:
                    f.write(str(data))
            try:
                with open(self.robot_status,'w',encoding='utf-8') as f:
                    f.write('1')
            except:
                with open(self.robot_status,'wb') as f:
                    f.write('1')
                
                
            
        except Exception as e:
            # 子流程:error
            self.__logger.debug('Flow:Main,StepNodeTag:171647142898,Note:进入异常流程处理')
            (temptemp)=self.error(detail=None,text='主流程异常')
        finally:
            # 代码块
            self.__logger.debug('Flow:Main,StepNodeTag:1716474227310,Note:关闭浏览器')
            import os
            os.system("taskkill /im chrome.exe")
            os.system("taskkill /im iexplore.exe")
 
if __name__ == '__main__':
    robot_no = ''
    proc_no = ''
    job_no = ''
    input_arg = ''
    try:
        argv = sys.argv[1:]
        opts, args = getopt.getopt(argv,"hr:p:j:i:",["robot = ","proc = ","job = ","input = "])
    except getopt.GetoptError:
        print ('robot.py -r <robot> -p <proc> -j <job>')
    for opt, arg in opts:
        if opt == '-h':
            print ('robot.py -r <robot> -p <proc> -j <job>')
        elif opt in ("-r", "--robot"):
            robot_no = arg
        elif opt in ("-p", "--proc"):
            proc_no = arg
        elif opt in ("-j", "--job"):
            job_no = arg
        elif opt in ("-i", "--input"):
            input_arg = arg
    pro = Dserver(robot_no=robot_no,proc_no=proc_no,job_no=job_no,input_arg=input_arg)
    pro.Main()
